package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.AccessManager;
import com.lvy.hczn.front.system.domain.business.Warehouse;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.transmit.service.TAccessManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class TAccessManagerServiceImpl implements TAccessManagerService {

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private WarehouseService warehouseService;

    /**
     * 货箱租赁单门禁同步
     * <p>
     * 根据仓库编号，获取所属区域编号，若是传过来的仓库编号为前置仓，需查总仓
     * 关联关系：前置仓关联总仓，总仓关联区域
     *
     * @param info
     * @return void
     * @author yw
     * @date 2023-05-23 21:16:15
     */
    @Override
    public synchronized void syncBoxLeasePlatform(ParamInfo<AccessManager> info) {
        if (info.getData() == null) {
            throw new UtilException("参数异常");
        }
        log.error("syncBoxLeasePlatform:{}", JSON.toJSONString(info));
        if (StrUtil.isEmpty(info.getWarehouseCode())) {
            throw new UtilException("仓库编码为空");
        }
        if (StrUtil.isEmpty(info.getData().getSourceCode())) {
            throw new UtilException("来源编号为空");
        }
        /*if (StrUtil.isEmpty(info.getData().getImgUrl())) {
            throw new UtilException("二维码图片为空");
        }*/
        if (info.getData().getType() == null) {
            throw new UtilException("类型为空");
        }

        Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, info.getWarehouseCode()).eq(Warehouse::getStatus, Constants.WAREHOUSE_STATUS_ENABLE).last("limit 1"));
        if (warehouse != null) {
            String topic = warehouseService.selectRegionAreaTopic(warehouse);
            String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_LEASE;
            try {
//                info.getData().setType(Constants.ACCESS_TYPE_FOUR);
                producerUtil.sendMsg(topic, tag, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
            } catch (Exception e) {
                throw new UtilException("数据转发异常");
            }
        } else {
            throw new UtilException("仓库信息不存在或已停用");
        }
    }
}
